package com.summer.common.lib.config;

import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

public class ConfigLoader {

    public static final String NAME = ConfigLoader.class.getName();

    Logger logger = Logger.getLogger(NAME);

    /**
     * 排序后，按照顺序，会覆盖重复的key，
     */
    private Map<String, Object> applicationConfigMap = new ConcurrentHashMap<>();

    /**
     * 按照配置文件名区分，不会覆盖key
     */
    private Map<String, Map<String, Object>> configLoaderTemplateMap = new ConcurrentHashMap<>();

    private static Comparator<ConfigLoaderTemplate> configComparator = (o1, o2) -> Integer.compare(o2.getOrdinal(), o1.getOrdinal());

    private List<ConfigLoaderTemplate> configSources = new LinkedList<>();

    public ConfigLoader() {
        init();
    }

    public synchronized void init() {
        // 加载所有扩展配置类
        ServiceLoader<ConfigLoaderTemplate> expandConfigLoader = ServiceLoader.load(ConfigLoaderTemplate.class);
        expandConfigLoader.forEach(configSources::add);
        configSources.sort(configComparator);
        configSources.forEach(configExpand -> {
            try (InputStream inputStream = this.getClass()
                    .getClassLoader()
                    .getResourceAsStream(configExpand.getConfigName())) {
                Yaml yaml = new Yaml();
                Map<String, Object> configContent = yaml.load(inputStream);
                applicationConfigMap.putAll(configContent);
                configLoaderTemplateMap.put(configExpand.getConfigName(), configContent);
            } catch (IOException e) {
                logger.severe("加载配置文件失败" + e.getMessage());
            }
        });
    }


    public Map<String, Object> getApplicationConfigMap() {
        return applicationConfigMap;
    }

    public Map<String, Map<String, Object>> getConfigLoaderTemplateMap() {
        return configLoaderTemplateMap;
    }

}
